package com.zmc.admin.infrastructure.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zmc.admin.infrastructure.bean.query.SysUserQuery;
import com.zmc.admin.infrastructure.entity.SysPostEntity;
import com.zmc.admin.infrastructure.entity.SysRoleEntity;
import com.zmc.admin.infrastructure.entity.SysUserEntity;
import com.zmc.admin.infrastructure.entity.SysUserRoleEntity;
import com.zmc.admin.infrastructure.service.*;
import com.zmc.common.exception.base.WebDisplayException;
import com.zmc.common.utils.PageUtils;
import com.zmc.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.zmc.admin.infrastructure.dao.SysUserDao;
import org.springframework.util.CollectionUtils;


/**
 * @author zmc
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {

    public static Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysPostService postService;

    @Autowired
    private SysConfigService configService;

    @Autowired
    private SysUserRoleService userRoleService;

    @Override
    public SysUserEntity validateUser(String username) {
        LambdaQueryWrapper<SysUserEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserEntity::getUserName, username).or()
                .eq(SysUserEntity::getPhonenumber, username).or()
                .eq(SysUserEntity::getEmail, username);
        return getOne(wrapper);
    }

    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRoleEntity> list = roleService.selectRolesByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRoleEntity::getRoleName).collect(Collectors.joining(","));
    }

    @Override
    public String selectUserPostGroup(String userName) {
        List<SysPostEntity> list = postService.selectPostsByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysPostEntity::getPostName).collect(Collectors.joining(","));
    }

    @Override
    public boolean checkPhoneUnique(SysUserEntity user) {
        LambdaQueryWrapper<SysUserEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserEntity::getPhonenumber, user.getPhonenumber());
        SysUserEntity one = getOne(wrapper);
        return one == null || Objects.equals(one.getUserId(), user.getUserId());
    }

    @Override
    public boolean checkEmailUnique(SysUserEntity user) {
        LambdaQueryWrapper<SysUserEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserEntity::getEmail, user.getEmail());
        SysUserEntity one = getOne(wrapper);
        return one == null || Objects.equals(one.getUserId(), user.getUserId());
    }

    @Override
    public int resetUserPwd(String userName, String newPassword) {
        return baseMapper.resetUserPwd(userName, newPassword);
    }

    @Override
    public boolean checkUserNameUnique(SysUserEntity user) {
        LambdaQueryWrapper<SysUserEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserEntity::getUserName, user.getUserName());
        SysUserEntity one = getOne(wrapper);
        return one == null || Objects.equals(one.getUserId(), user.getUserId());
    }

    @Override
    public boolean registerUser(SysUserEntity sysUser) {
        return baseMapper.insertUser(sysUser);
    }

    @Override
    public SysUserEntity selectUserByUserName(String userName) {
        LambdaQueryWrapper<SysUserEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserEntity::getUserName, userName);
        return getOne(wrapper);
    }

    @Override
    public List<SysUserEntity> selectAllocatedList(SysUserQuery user) {
        return baseMapper.selectAllocatedList(user);
    }

    @Override
    public List<SysUserEntity> selectUnallocatedList(SysUserQuery user) {
        return baseMapper.selectUnallocatedList(user);
    }

    @Override
    public PageUtils pageUserList(SysUserQuery query) {
        Page<SysUserEntity> page = baseMapper.selectPage(new Page<>(query.getPageNum(), query.getPageSize()), getWrapper(query));
        return new PageUtils(page);
    }

    @Override
    public List<SysUserEntity> selectUserList(SysUserQuery query) {
        return list(getWrapper(query));
    }

    //todo 先保留
    @Override
    public String importUser(List<SysUserEntity> userList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            log.error("导入用户数据不能为空！");
            throw new WebDisplayException("导入用户数据不能为空");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
       /* for (SysUserEntity user : userList)
        {
            try
            {
                // 验证是否存在这个用户
                SysUserEntity u = selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u))
                {
                    BeanValidators.validateWithException(validator, user);
                    String password = configService.selectConfigByKey("sys.user.initPassword");
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    userMapper.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    BeanValidators.validateWithException(validator, user);
                    checkUserAllowed(u);
                    checkUserDataScope(u.getUserId());
                    deptService.checkDeptDataScope(user.getDeptId());
                    user.setUserId(u.getUserId());
                    user.setUpdateBy(operName);
                    userMapper.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }*/
        return successMsg.toString();
    }

    @Override
    public void insertUserAuth(Long userId, Long[] roleIds) {
        userRoleService.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    @Override
    public SysUserEntity getMerchantId(String merchantId) {
        LambdaQueryWrapper<SysUserEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserEntity::getMerchantId, merchantId).last(" limit 1");
        return getOne(wrapper);
    }

    /**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds) {
        if (StringUtils.isNotEmpty(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRoleEntity> list = new ArrayList<SysUserRoleEntity>(roleIds.length);
            for (Long roleId : roleIds) {
                SysUserRoleEntity ur = new SysUserRoleEntity();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleService.saveBatch(list);
        }
    }

    private LambdaQueryWrapper<SysUserEntity> getWrapper(SysUserQuery query) {
        LambdaQueryWrapper<SysUserEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.isNotEmpty(query.getUserName()), SysUserEntity::getUserName, query.getUserName())
                .eq(StringUtils.isNotEmpty(query.getPhonenumber()), SysUserEntity::getPhonenumber, query.getPhonenumber())
                .ge(StringUtils.isNotEmpty(query.getBeginTime()), SysUserEntity::getCreateTime, query.getBeginTime())
                .le(StringUtils.isNotEmpty(query.getEndTime()), SysUserEntity::getCreateTime, query.getEndTime());
        return wrapper;
    }

}